package com.niiwoo.civet.user.service.duboo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.niiwoo.civet.trade.service.configure.TradeConfigDubboService;
import com.niiwoo.civet.trade.service.loan.SpeedLoanDubboService;
import com.niiwoo.civet.user.dao.entity.DataStatus;
import com.niiwoo.civet.user.dto.response.ThirdAuthResponseDTO;
import com.niiwoo.civet.user.dto.response.UserRealNameInfoDTO;
import com.niiwoo.civet.user.dto.response.ZhiMaScoreResponseDTO;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.service.UserAuthZhiMaDubboService;
import com.niiwoo.civet.user.service.local.UserAuthCommonService;
import com.niiwoo.civet.user.service.local.UserAuthorizationInfoService;
import com.niiwoo.civet.user.service.local.UserDataService;
import com.niiwoo.civet.user.service.local.UserStatusService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import com.niiwoo.tripod.tiancheng.component.TianchengAuthZhiMaService;
import com.niiwoo.tripod.tiancheng.request.auth.ZhiMaDataRequest;
import com.niiwoo.tripod.tiancheng.response.auth.ZhiMaDataResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service(version = "1.0.0")
public class UserAuthZhiMaDubboServiceImpl implements UserAuthZhiMaDubboService {

    @Autowired
    private TianchengAuthZhiMaService tianchengAuthZhiMaService;

    @Autowired
    private UserDataService userDataService;

    @Autowired
    private UserStatusService userStatusService;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    PrivacyMasks privacyMasks;

    @Reference(version = "1.0.0")
    private TradeConfigDubboService tradeConfigDubboService;

    @Reference(version = "1.0.0")
    private SpeedLoanDubboService speedLoanDubboService;

    @Value(value = "${web-http-url}")
    private String webHttpUrl;

    @Autowired
    private UserAuthorizationInfoService userAuthorizationInfoService;

    /**
     * 芝麻回调授权成功通知地址
     */
    private final String ZHI_MA_NOTIFY_URL = "/tc/authZhiMaNotify/callback";



    @Autowired
    private UserAuthCommonService userAuthCommonService;

    /**
     * 获取天秤第三方授权h5页面的url
     *
     * @param userId   用户id
     * @param createIp 用户客户端请求ip
     * @return com.niiwoo.civet.user.dto.response.ThirdAuthResponseDTO
     * @author zzl
     * @date 2017/11/22 16:20
     */
    @Override
    public ThirdAuthResponseDTO getThirdAuthUrl(String userId, String createIp) {
        DataStatus existsUserIdAndType = userStatusService.getByUserIdAndType(userId, UserDataTypeEnum.ZHIMA_AUTHORIZE);
        if (existsUserIdAndType != null) {
            //已授权或已验证，直接返回
            if (UserDataStatusEnum.ZhimaCreditStatus.PASS_APPLY.getStatus().equals(existsUserIdAndType.getDataStatus())) {
                ThirdAuthResponseDTO dto = new ThirdAuthResponseDTO();
                //已授权
                dto.setStatus(UserDataStatusEnum.ZhimaCreditStatus.PASS_APPLY.getStatus().toString());
                return dto;
            }
        }
        return userAuthCommonService.getThirdAuthUrl(userId, createIp, tianchengAuthZhiMaService, webHttpUrl + ZHI_MA_NOTIFY_URL, null);
    }

    @Override
    public ZhiMaScoreResponseDTO getZhiMaScore(String userId) {

        UserRealNameInfoDTO userRealNameInfoDTO = userDataService.getUserRealNameInfo(userId);
        if (userRealNameInfoDTO == null) {
            return null;
        }
        if (StringUtils.isBlank(userRealNameInfoDTO.getRealName())
                || StringUtils.isBlank(userRealNameInfoDTO.getIdCard())) {
            return null;
        }
        ZhiMaDataRequest zhiMaDataRequest = new ZhiMaDataRequest();
        zhiMaDataRequest.setIdentityCard(privacyMasks.decryptPrivacy(userRealNameInfoDTO.getIdCard()));
        zhiMaDataRequest.setRealName(userRealNameInfoDTO.getRealName());
        zhiMaDataRequest.setTransDate(new Date());
        zhiMaDataRequest.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));

        CompletableFuture<ZhiMaDataResponse> future = tianchengAuthZhiMaService.queryZhiMaScore(zhiMaDataRequest);


        try {
            ZhiMaScoreResponseDTO responseDTO = new ZhiMaScoreResponseDTO();
            int timeout = 5;
            ZhiMaDataResponse response = future.get(timeout, TimeUnit.SECONDS);
            responseDTO.setScore(response.getScore());
            //暂不存库
            return responseDTO;
        } catch (Throwable e) {
            log.error("ZhiMaScore异常", e);
        }
        return null;
    }

    @Override
    public void updateZhiMaScore(String userId, String failureReason, UserDataStatusEnum.ZhimaCreditStatus statusEnum, Date authTime) {
        ZhiMaScoreResponseDTO zhiMaScoreResponseDTO = getZhiMaScore(userId);
        if (zhiMaScoreResponseDTO == null) {
            return;
        }
        userAuthorizationInfoService.saveUserZhiMaInfo(userId, NumberUtils.toInt(zhiMaScoreResponseDTO.getScore()), failureReason, statusEnum, authTime);
    }

    @Override
    public void saveZhiMaScore(String userId, Integer zhimaScore) {
        userAuthorizationInfoService.saveUserZhiMaInfo(userId, zhimaScore, null, UserDataStatusEnum.ZhimaCreditStatus.PASS_APPLY, new Date());
    }
}
